package cn.spring.com.eleven.service;

import cn.spring.com.spring.BeanPostProcessor;
import cn.spring.com.spring.Component;
import cn.spring.com.spring.ElevenApplicationContext;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component("ElevenBeanPostProcessor")
public class ElevenBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println("初始化之前调用");
        if(beanName.equals("userService")){
            ((UserService)bean).setName("newUserService");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("初始化之后调用");
        if(beanName.equals("userService")){
            // JDK的动态代理
            Object proxyInstance = Proxy.newProxyInstance(ElevenBeanPostProcessor.class.getClassLoader()
                    , bean.getClass().getInterfaces(), new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            System.out.println("JDK的动态代理");
                            return method.invoke(bean, args);
                        }
                    });
            return proxyInstance;
        }
        return bean;
    }
}
